import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:gim_plugin/gim_plugin.dart';
import 'package:gim_plugin_example/components/my_img.dart';
import 'package:gim_plugin_example/components/photo_view_modal.dart';
import 'package:gim_plugin_example/consts.dart';
import 'package:gim_plugin_example/utils/cache.dart';
import 'package:gim_plugin_example/utils/logger_utils.dart';
import 'package:provider/provider.dart';

import '../pg_chat_room_store.dart';
import 'msg_box.dart';

class ImgMsg extends StatelessWidget {
  final C2cMsg msg;

  ImgMsg({Key? key, required this.msg}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    ImageMsg img = ImageMsg.fromJson(json.decode(msg.msgData!));
    double maxSize = 140;
    double width = maxSize;
    double height = maxSize;
    double aspectRatio = img.width!/img.height!;
    if (aspectRatio > 1) {
      width = maxSize;
      height = maxSize / aspectRatio;
    } else if (aspectRatio < 1) {
      height = maxSize;
      width = height * aspectRatio;
    }
    return MsgBox(
        msg: msg,
        padding: 0,
        bgColor: Colors.transparent,
        onTap: () {
          PgChatRoomStore store = context.read<PgChatRoomStore>();
          List<String> urlList = [];
          for (var item in store.msgList) {
            if (item.msgType == MsgTypes.MsgTypeImage) {
              ImageMsg imageMsg = ImageMsg.fromJson(json.decode(item.msgData!));
              urlList.add(imageMsg.url!);
            }
          }
          photoViewModal.open(context, photos: urlList, initIndex: urlList.indexOf(img.url!));
        },
        child: ClipRRect(
          borderRadius: msg.fromUid == cache.getStringSync(UID)
              ? const BorderRadius.only(
              topLeft: Radius.circular(10), bottomLeft: Radius.circular(10), bottomRight: Radius.circular(10))
              : const BorderRadius.only(
              topRight: Radius.circular(10), bottomLeft: Radius.circular(10), bottomRight: Radius.circular(10)),
          child: myImg(img.url!, width: width, height: height),
        ));
  }
}
